package uk.ac.cam.cl.android.jwdb;

import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;

class SwipeGestureDetector extends SimpleOnGestureListener {
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private Action listener;
    private int direction;
    
    public SwipeGestureDetector(int direction, Action listener) {
    	this.listener = listener;
    	this.direction = direction;
    }
    
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH && (direction == 0 || direction == 1))
                return false;
            if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH && (direction == 2 || direction == 3))
                return false;
            // right to left swipe
            if(direction == 0 && e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("Swipe", "Left!");
                listener.done();
            }  else if (direction == 1 && e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("Swipe", "Right!");
                listener.done();
            }  else if (direction == 2 && e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("Swipe", "Up!");
                listener.done();
            }  else if (direction == 3 && e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("Swipe", "Down!");
                listener.done();
            }
        } catch (Exception e) {
            // nothing
        }
        return false;
    }

}
